package com.acoreful.ackitcloud.api.config;

import com.acoreful.ackitcloud.api.PmsBrandApi;
import com.acoreful.ackitcloud.api.UmsAdminApi;
import com.acoreful.ackitcloud.api.holder.TokenHolder;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.client.ClientRequest;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.support.WebClientAdapter;
import org.springframework.web.service.invoker.HttpServiceProxyFactory;

@Configuration(proxyBeanMethods = false)
@RequiredArgsConstructor
public class HttpInterfaceConfig {

    private final static String HEADER_SOURCE="source";
    private final static String HEADER_AUTH="Authorization";
    @Value("${remote.baseUrl:}")
    private String baseUrl;

    private final TokenHolder tokenHolder;

    @Bean
    public WebClient webClient(){
        return WebClient.builder()
                .defaultHeader(HEADER_SOURCE,HeaderSource.HTTP_INTERFACE)
                .filter(((request, next) -> {
                    ClientRequest filtered= ClientRequest.from(request)
                            .header(HEADER_AUTH,tokenHolder.getToken()).build();
                    return next.exchange(filtered);
                })).baseUrl(baseUrl).build();
    }
    @Bean
    UmsAdminApi umsAdminApi(WebClient client){
        return this.createServiceClient(client,UmsAdminApi.class);
    }
    @Bean
    PmsBrandApi pmsBrandApi(WebClient client){
        return this.createServiceClient(client,PmsBrandApi.class);
    }

    private <S> S createServiceClient(WebClient client,Class<S> serviceType){
        return HttpServiceProxyFactory.builder(WebClientAdapter.forClient(client)).build().createClient(serviceType);
    }


    public interface HeaderSource{
        public final String HTTP_INTERFACE="http-interface";
    }

}
